import {
  _decorator,
  Component,
  SpriteFrame,
  resources,
  Sprite,
  floatToHalf,
} from 'cc';

const { ccclass, property } = _decorator;
import { PlantAction,CommonData } from './Utils/CommonData'



@ccclass('PlantBase')
export default class PlantBase extends Component {


  @property
  maxHp:number = 100

  @property()
  frameRate: number = 0.1;

  private hp:number = 0
  protected sprite: Sprite = null;
  _currentAction: PlantAction = 'idle';
  _frameIndex: number = 0;
  _timer: number = 0;

  public async init(plantName: string, sprite: Sprite) {
    this.hp = this.maxHp
    this.sprite = sprite;
    if(CommonData.instance.plantFramesMap.get(this.node.name).get('idle').length) {
      this.sprite.spriteFrame = CommonData.instance.plantFramesMap.get(this.node.name).get('idle')[0]
    }
  }

  protected loadFrames(
    plantName: string,
    action: PlantAction
  ): Promise<SpriteFrame[]> {
    return new Promise((resolve, reject) => {
      const path = `texture/plants/${plantName}/${action}`;
      resources.loadDir(path, SpriteFrame, (err, assets) => {
        if (err) {
          console.warn(`加载 ${plantName}/${action} 失败`, err);
          resolve([]);
          return;
        }
        resolve(assets as SpriteFrame[]);
      });
    });
  }

  protected update(dt: number): void {
    this.updateAnimation(dt);
    this.onUpdate(dt);
  }

  updateAnimation(dt: number) {
    const frames = CommonData.instance.plantFramesMap.get(this.node.name).get(this._currentAction)
    if (!frames || frames.length <= 1) return;
    this._timer += dt;
    if (this._timer >= this.frameRate) {
      this._timer = 0;
      this._frameIndex++;
      if (this._frameIndex >= frames.length) this._frameIndex = 0;
      if (this.sprite) {
        this.sprite.spriteFrame = frames[this._frameIndex];
      }
    }
  }

  playAction(action: PlantAction) {
    if (this._currentAction === action) return;
    this._currentAction = action;
    this._frameIndex = 0;
    this._timer = 0;
    const frames = CommonData.instance.plantFramesMap.get(this.node.name).get(action)
    if (frames && frames.length > 0) {
      this.sprite.spriteFrame = frames[0];
    }
  }

  protected onInit() {}

  protected onUpdate(dt: number) {}
}
